package com.derbysoft.synxisadapter.commons.log;

import com.derbysoft.synxisadapter.commons.model.OperationType;
import com.derbysoft.synxisadapter.commons.model.TransactionLog;
import com.derbysoft.synxisadapter.commons.repository.ReservationRepository;
import com.derbysoft.synxisadapter.commons.repository.TransactionLogRepository;

import java.util.Set;
import java.util.concurrent.Executor;

/**
 * Created by: jason
 * Date: 2012-09-25
 */
public abstract class LogUtils {
    public static void saveAvailLogs(Executor executor, TransactionLogRepository transactionLogRepository) {
        TransactionLog transactionLog = TransactionLogger.getTransactionLogger().get();
        Set<LogDetailPair> logDetailPairs = TransactionLogger.getLogDetails().get();

        if (transactionLog == null) {
            return;
        }
        if (failedAvailResponse(transactionLog)) {
            executor.execute(new TransactionLogTask(transactionLogRepository, transactionLog, logDetailPairs));
            TransactionLogger.cleanAvailLogger();
        }
        TransactionLogger.cleanLogDetails();
    }

    public static void saveReservationLogs(Executor executor, TransactionLogRepository transactionLogRepository,
                                           ReservationRepository reservationRepository) {
        TransactionLog transactionLog = TransactionLogger.getTransactionLogger().get();
        Set<LogDetailPair> logDetailPairs = TransactionLogger.getLogDetails().get();

        if (transactionLog == null) {
            return;
        }
        executor.execute(new TransactionLogTask(transactionLogRepository, transactionLog, logDetailPairs));

        ReservationPair reservationPair = TransactionLogger.getReservationLogger().get();
        if (reservationPair == null) {
            return;
        }

        executor.execute(new ReservationLogTask(reservationRepository, reservationPair, logDetailPairs));

        TransactionLogger.cleanAvailLogger();

        TransactionLogger.cleanReservationLogger();

        TransactionLogger.cleanLogDetails();
    }

    private static boolean failedAvailResponse(TransactionLog transactionLog) {
        return transactionLog.getOperationType() == OperationType.HOTEL_AVAIL && transactionLog.isError();
    }
}
